package tracker.jira;

object JiraIntegration {
  
  import com.atlassian.jira.rpc.soap._
  import com.atlassian.jira.rpc.soap.beans._
  import bamboo.util._
  import tracker.model._
  import tracker.ui.Main._
  
  val jira = new JiraSoapServiceServiceLocator().getJirasoapserviceV2;
  
  def logActivities(login: String, password: String, activities: Iterable[Activity]) = {
    val token = jira.login(login, password)
    activities.foreach { a =>
      try {
        logActivity(token, a)
      } catch {
        case e => println(e.toString())
      }
    }
  }
  
  def toJiraString(span: TimeSpan) = {
    val elements = span.toString().split(":")
    elements(0) + "h " + elements(1) + "m"
  }  
  
  val JiraTicketPattern = java.util.regex.Pattern.compile("[A-Z]+-\\d+")

  def jiraTicketFrom(s: String): String = {
    val matcher = JiraTicketPattern.matcher(s)
    if (matcher.find) matcher.group else null
  }
  
  def logWorkDone(loginToken: String, issue: String, when : java.util.Date, time: TimeSpan, comment: String) = {
    val worklog = new RemoteWorklog()
    
    worklog.setComment(comment)
    worklog.setTimeSpent(toJiraString(time))
    worklog.setStartDate(new java.util.GregorianCalendar(when.getYear() + 1900, when.getMonth(), when.getDate()))
    
    jira.addWorklogAndRetainRemainingEstimate(loginToken, issue, worklog)
  }

  def logActivity(loginToken: String, a: Activity): Unit = {
    val marker = "*jiraed*"
    val notes = a.notes
    if (notes eq null) {
      println("Nothing to log for " + a + ".")
      return
    }
    
    if (notes.contains(marker)) {
      println("" + a  + " already logged.")
      return
    }
      
    val ticket = jiraTicketFrom(notes)
    if (ticket eq null) {
      println("No jira ticket for " + a + ".")
      return
    }
    
    println("Loging: " + ticket)
    logWorkDone(loginToken, ticket, a.finished, a.elapsed, notes)
    a.notes = notes + " " + marker
    system.update(a)
    println("Logged " + a + " for ticket " + ticket + ".")
  }
  
  def println(s: String) = {
    interpreter.append(s + "\n")
  }

}
